package leetcode.code0809;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	class Node {
		char c;
		Node next;
		int size;

		public void add(String s) {
			Node node = this;
			char[] cs = s.toCharArray();
			int p = 0, len = cs.length;
			while (p < len) {
				char c = cs[p];
				int r = p;
				while (r < len && cs[r] == c) {
					r++;
				}
				node.c = c;
				node.size = r - p;
				node.next = new Node();
				node = node.next;
				p = r;
			}
		}

		public int match(String word) {
			Node node = this;
			char[] cs = word.toCharArray();
			int p = 0, len = cs.length;
			while (p < len) {
				char c = cs[p];
				int r = p;
				while (r < len && cs[r] == c) {
					r++;
				}
				int size = r - p;
				if (node.size == 0 || node.c != c || (node.size <= 2 && node.size != size)
						|| (node.size > 2 && size > node.size)) {
					return 0;
				}
				node = node.next;
				p = r;
			}
			return node.size == 0 ? 1 : 0;
		}

	}

	public int expressiveWords(String s, String[] words) {
		Node root = new Node();
		root.add(s);
		int ans = 0;
		for (String word : words) {
			ans += root.match(word);
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(0, this.expressiveWords("abcd", H.str2array2("[\"abc\"]")));
		H.compare(3,
				this.expressiveWords("heeellooo", H.str2array2("[\"hello\",\"heeello\",\"heelloo\",\"heeloo\"]")));
		H.compare(1, this.expressiveWords("heeellooo", H.str2array2("[\"hello\",\"hi\",\"helo\"]")));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
